import axios from 'axios'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import {msgBoxNoLogin, msgBoxNoRole, msgError} from './dw-msg'

export function ourl() {
  return oUrl
}
export function fileurl() {
  return fileUrl
}
export function compileurl(){
  return compileUrl;
}
export function UEditorurl() {
  return UEditorUrl
}


// 不可删除！ 不可修改！
var oUrl = process.env.VUE_APP_BASE_API
var fileUrl = process.env.VUE_APP_URL_FILE
var compileUrl = process.env.VUE_APP_URL_COMPILE;//汇编地址
var UEditorUrl = process.env.VUE_APP_URL_UEDITOR;//富文本

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 60000
})
// request拦截器
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = 'Bearer ' + getToken();
    } else {
      config.headers['Authorization'] = 'Basic ' + window.btoa('webapp:123456')
    }
    return config
  },
  error => {
    // console.log(error)
    // Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    console.debug('response')
    console.debug(response)
    if (response.status === 200) {
      const {data} = response
      if (data.hasOwnProperty('resultCode')) {
        if (data.resultCode === 401) {
          msgBoxNoLogin()
        } else if (data.resultCode === 403) {
          msgBoxNoRole()
        } else if (data.resultCode !== 200) {
          let message = `异常码：${data.resultCode}`
          if (data.hasOwnProperty('resultMsg')) {
            message = `${data.resultMsg}，异常码：${data.resultCode}`
          }
          msgError(message)
        }
      }
      return Promise.resolve(response)
    } else {
      return Promise.reject(response)
    }
  },
  error => {
    // 服务器状态码不是200的情况
    console.log('err' + error)
    let {message} = error
    if (message.includes('Network Error')) {
      message = '网络异常，请稍候再试'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      const code = message.substr(message.length - 3)
      if (code === '401' || code === '403') {
        message = null
        if (code === '401') {
          msgBoxNoLogin()
        } else if (code === '403') {
          msgBoxNoRole()
        }
      } else {
        message = '系统接口' + message.substr(message.length - 3) + '异常'
      }
    }
    if (message != null) {
      msgError(message)
    }
    return Promise.reject(error)
  }
)

export default service

